package cc.dowell.service.Impl;

import cc.dowell.vo.echart.Option;
import cc.dowell.vo.echart.Serie;
import cc.dowell.vo.echart.XAxis;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cc.dowell.config.ContextHolder;
import cc.dowell.mapper.HistoryMapper;
import cc.dowell.pojo.History;
import cc.dowell.service.HistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Autowired
    private HistoryMapper historyMapper;

    @Override
    public IPage<History> selectHistoryPage(Page<History> page,
                                            String beginDate, String endDate, String varietyCode) {

        LambdaQueryWrapper<History> lqw = new LambdaQueryWrapper<>();
        Long userId = ContextHolder.getUserId();
        lqw.eq(History::getCreateUserId, userId);
        lqw.ge(beginDate!=null && beginDate.length()>0,History::getCreateTime,beginDate);
        lqw.le(endDate!=null && endDate.length()>0,History::getCreateTime,endDate);
        lqw.eq(varietyCode!=null && varietyCode.length()>0,History::getVarietyCode,varietyCode);
        lqw.orderByDesc(History::getCreateTime);
        Page<History> historyPage = historyMapper.selectPage(page, lqw);

        return historyPage;

    }

    @Override
    public Option getCountByMonth() {
        int thisYear = DateUtil.thisYear();
        int thisMonth = DateUtil.thisMonth();  //从0开始
        List<Map<String, Integer>> dataList = historyMapper.getCountByMonth(thisYear, thisMonth);
        //获取本月的天数
        Calendar cal = Calendar.getInstance();
        cal.set(thisYear,thisMonth,1);
        int dayOfMonth = DateUtil.lengthOfMonth(thisMonth,DateUtil.isLeapYear(thisYear));
        List<Map<String, Integer>> dataListFullMonth = new ArrayList<>();
        for (int i = 1; i <= dayOfMonth; i++) {
            Map<String, Integer> dataItem = new HashMap<>();
            dataItem.put("d",i);
            dataItem.put("count",0);
            dataListFullMonth.add(dataItem);
        }
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Integer> mapItem = dataList.get(i);
            int day = mapItem.get("d");
            Map<String, Integer> mapItem2 = dataListFullMonth.get(day - 1);
            mapItem2.replace("count",mapItem.get("count"));
        }

        //为了数据从大到小排列
//        Collections.sort(dataList, (o1, o2) -> {
//            return -1;
//        });
        //创建Option
        Option option = new Option();
        //类别
        XAxis xAxis = new XAxis();
        //系列
        Serie serie = new Serie();
        serie.setName("次数");
        serie.setType("bar");
//        serie.setBarWidth("18");
        for (Map<String, Integer> map : dataListFullMonth) {
            xAxis.getData().add(map.get("d"));
            serie.getData().add(map.get("count"));
        }

        // 设置系列数据
        option.getSeries().add(serie);
        // 设置x轴
        option.setXAxis(xAxis);
        log.info("option=" + JSON.toJSON(option));
        return option;

    }

    @Override
    public Option getCountByVariety() {

        List<Map<String, Integer>> countByVariety = historyMapper.getCountByVariety();

        Option option = new Option();
        //系列
        Serie serie = new Serie();
        serie.setName("各类别果蔬检测情况");
        serie.setType("pie");
        serie.getData().add(countByVariety);
        // 设置系列数据
        option.getSeries().add(serie);
        log.info("option=" + JSON.toJSON(option));
        return option;
    }

    /**
     * option数据的格式：
     *
     *
     */
    @Override
    public Option getMatureRate() {
        Option option = new Option();
        //图标的系列数据
        //List<Map<String, Object>> serieData = new ArrayList<>();
        List<Map<String, Object>> matureRateData = historyMapper.getMatureRateByDays();

        //生成果蔬成熟率输出的map
        for (Map<String, Object> map : matureRateData) {
            HashMap<String, Object> varietyMatureRateMap = new HashMap<>();
            //放入name
            String varietyCode = (String)map.get("variety_code");
            varietyMatureRateMap.put("name",varietyCode);
            //放入data ,5个时间间隔的数据（30天，20天，15天，10天，5天）
            //BigDecimal plantId1 = (BigDecimal)

            BigDecimal matureRate5 = (BigDecimal) map.get("mature_rate5");
            BigDecimal matureRate10 =  (BigDecimal) map.get("mature_rate10");
            BigDecimal matureRate15 =  (BigDecimal) map.get("mature_rate15");
            BigDecimal matureRate20 =  (BigDecimal) map.get("mature_rate20");
            BigDecimal matureRate30 =  (BigDecimal) map.get("mature_rate30");
            ArrayList<Object> rateList = new ArrayList<>();
            rateList.add(matureRate30.doubleValue());
            rateList.add(matureRate20.doubleValue());
            rateList.add(matureRate15.doubleValue());
            rateList.add(matureRate10.doubleValue());
            rateList.add(matureRate5.doubleValue());
            varietyMatureRateMap.put("data",rateList);
            //系列
            Serie serie = new Serie();
            serie.setName(varietyCode);
            serie.setType("line");
            serie.setData(rateList);
            option.getSeries().add(serie);
            //将map放入List
//            serieData.add(varietyMatureRateMap);
        }

        // for (Map<String, Object> serieMap : serieData) {
        //     System.out.println(serieMap);
        // }

        // 设置系列数据

        log.info("option=" + JSON.toJSON(option));
        return option;
    }


}
